//
//  JHCharacterViewController.m
//  Liberty Voice
//
//  Created by dlios on 15-5-13.
//  Copyright (c) 2015年 ClearLove. All rights reserved.
//

#import "JHCharacterViewController.h"
#import "JHCharacterView.h"
#import "JHCharacterTableViewCell.h"
#import "JHCharacterObject.h"
#import "JHPicTableViewCell.h"
#import "NetwordHandler.h"
#import "MJRefresh.h"
#import "MONActivityIndicatorView.h"
#import "PendulumView.h"

@interface JHCharacterViewController ()<UITableViewDataSource, UITableViewDelegate, MONActivityIndicatorViewDelegate>

@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSMutableArray *picArr1;
@property (nonatomic, retain) NSString *s;
@property (nonatomic, retain) PendulumView *pendulum ;
@end

@implementation JHCharacterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.arr = [NSMutableArray array];
    self.picArr1 = [NSMutableArray array];
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"段子", @"图片"]];
    self.navigationItem.titleView = seg;
    seg.frame = CGRectMake(0, 0, 200, 35);
    seg.selectedSegmentIndex = 0;
    seg.tintColor = [UIColor lightGrayColor];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];

    [seg release];

    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    view1.tag = 2001;
    [self.view addSubview:view1];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    view2.backgroundColor = [UIColor orangeColor];
    view2.tag = 2002;
    [self.view addSubview:view2];

    self.tableView1 = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 105) style:UITableViewStylePlain];
    _tableView1.delegate = self;
    _tableView1.dataSource = self;
    _tableView1.tag = 4444;
   
    [view1 addSubview:_tableView1];
    // 分割线颜色
    _tableView1.separatorColor = [UIColor whiteColor];
    [_tableView1 release];
    
    
    [self.view bringSubviewToFront:view1];
    [self addHeader];
    [self addFooter];
    [self creatTableView];


     [self dian];

    
}
//- (void)dian
//{
//    // 加载
//    self.indicatorView = [[MONActivityIndicatorView alloc] init];
//    _indicatorView.delegate = self;
//    _indicatorView.numberOfCircles = 5;
//    _indicatorView.radius = 10;
//    _indicatorView.internalSpacing = 10;
//    _indicatorView.center = self.tableView1.center;
//    [_indicatorView startAnimating];
//    [self.view addSubview:_indicatorView];
////    
////    [NSTimer scheduledTimerWithTimeInterval:2 target:_indicatorView selector:@selector(stopAnimating) userInfo:nil repeats:YES];
//    //    [NSTimer scheduledTimerWithTimeInterval:9 target:_indicatorView selector:@selector(startAnimating) userInfo:nil repeats:YES];
//    
//}
// 加载
//- (UIColor *)activityIndicatorView:(MONActivityIndicatorView *)activityIndicatorView
//      circleBackgroundColorAtIndex:(NSUInteger)index {
//    CGFloat red   = (arc4random() % 256)/255.0;
//    CGFloat green = (arc4random() % 256)/255.0;
//    CGFloat blue  = (arc4random() % 256)/255.0;
//    CGFloat alpha = 1.0f;
//    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
//}
 - (void)boll
{
    CGFloat red   = (arc4random() % 256)/255.0;
    CGFloat green = (arc4random() % 256)/255.0;
    CGFloat blue  = (arc4random() % 256)/255.0;
    UIColor *ballColor = [UIColor colorWithRed:red green:green blue:blue alpha:1];
    self.pendulum = [[PendulumView alloc] initWithFrame:self.view.bounds ballColor:ballColor];
    [self.view addSubview:_pendulum];

}
- (void)creatTableView
{
    self.tableView2 = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    _tableView2.delegate = self;
    _tableView2.dataSource = self;
    _tableView2.tag = 5555;
    [[self.view viewWithTag:2002] addSubview:_tableView2];
    // 分割线颜色
    _tableView2.separatorColor = [UIColor lightGrayColor];
    [_tableView2 release];

}

- (void)segAction:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex == 0) {
        [self.view bringSubviewToFront:[self.view viewWithTag:2001]];
    }else{
        [self.view bringSubviewToFront:[self.view viewWithTag:2002]];
        [self boll];
        [self addoneHeader];
        [self addoneFooter];
        [_tableView2 reloadData];
    }
   
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView1) {
        CGFloat f = [JHCharacterTableViewCell heightWithText:_arr[indexPath.row]];
        return f + 40;
    }else if (tableView == _tableView2){
        CGFloat f1 = [JHPicTableViewCell heightWithText:[_picArr1[indexPath.row] text]];
        JHCharacterObject *s = [[JHCharacterObject alloc] init];
        s = _picArr1[indexPath.row];
        CGFloat biLi =  [s.height floatValue] / [s.width floatValue] ;
        CGFloat f2 = (self.view.frame.size.width - 10) *biLi;
        
        return f1 + f2 + 30;
        
    }
    return 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _tableView1) {
        return _arr.count;

    }else if (tableView == _tableView2){
        return _picArr1.count;
    }
    return 0;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == _tableView1) {
    static NSString *reuse = @"reuse";
    JHCharacterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[JHCharacterTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse]autorelease];
    }
    cell.myLabel1.text = _arr[indexPath.row];
    return cell;
    }
//    cell.myLabel2.text = @"哈哈";
    else if (tableView == _tableView2){
        static NSString *reuse = @"reuses";
        JHPicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (cell == nil) {
            cell = [[[JHPicTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse]autorelease];
        }
        cell.objc = _picArr1[indexPath.row];
        
        return cell;
    }
    return nil;
}


+ (CGFloat)heightWithText:(NSString *)text
{
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:14]};
    CGSize size = CGSizeMake(330, 1000);
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesDeviceMetrics attributes:dic context:nil];
    return rect.size.height;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消选中阴影效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
- (void)addHeader
{
        __block JHCharacterViewController *hotUser = self;
        [self.tableView1 addHeaderWithCallback:^{
            hotUser.isUpLoading = NO;
            [hotUser GetPersonList:1];//重新请求数据
        }];
        [self.tableView1 headerBeginRefreshing];
}

- (void)addFooter
{
        __block JHCharacterViewController *hotUser = self;
        [self.tableView1 addFooterWithCallback:^{
            hotUser.isUpLoading = YES;
            [hotUser GetPersonListf:(hotUser.nextCursor++) + 1];
        }];
        [self.tableView1 footerBeginRefreshing];
    
}
- (void)GetPersonList:(NSInteger)nextCursor
{
        /**
         *  拼接页数
         */
        NSString *url_string = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&asid=A25D4B33-B4E7-4855-9693-958D39D4E41B&c=data&openudid=f5a57d94b5a673c7472c065d701188ee6c31df16&page=%ld& type=29",nextCursor];
        // 获取网络数据
        [NetwordHandler requestWithURL:url_string completion:^(id result) {
            NSDictionary *dic = result;
            NSLog(@"%@",result);
            if (self.isUpLoading == NO) {
                //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
                [self.arr removeAllObjects];
            }
            NSMutableArray *a = [NSMutableArray array];
            a = [dic objectForKey:@"list"];
            for (NSDictionary *d in a) {
                NSString *str = [d objectForKey:@"text"];
                [_arr addObject:str];
            }
            [self.tableView1 headerEndRefreshing];
            [self.tableView1 footerEndRefreshing];
            [self.tableView1 reloadData];
            
            [self.indicatorView removeFromSuperview];
            
            
        }];

}
- (void)GetPersonListf:(NSInteger)nextCursor
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&asid=A25D4B33-B4E7-4855-9693-958D39D4E41B&c=data&openudid=f5a57d94b5a673c7472c065d701188ee6c31df16&page=%ld& type=29",nextCursor];
    NSLog(@"===========%ld", nextCursor);
    // 获取网络数据
    [NetwordHandler requestWithURL:url_string completion:^(id result) {
        NSDictionary *dic = result;
        NSLog(@"%@",result);
        NSMutableArray *a = [NSMutableArray array];
        a = [dic objectForKey:@"list"];
        [a removeObjectAtIndex:0];
        for (NSDictionary *d in a) {
            NSString *str = [d objectForKey:@"text"];
            [_arr addObject:str];
        }
        [self.tableView1 footerEndRefreshing];
        [self.tableView1 reloadData];
     }];
}







- (void)addoneHeader
{
    __block JHCharacterViewController *jhc = self;
    [self.tableView2 addHeaderWithCallback:^{
        jhc.isUpLoading = NO;
        [jhc GetPersonListone:1];//重新请求数据
    }];
    [self.tableView2 headerBeginRefreshing];

}
- (void)addoneFooter
{
    __block JHCharacterViewController *jhc = self;
    [self.tableView2 addFooterWithCallback:^{
        jhc.isUpLoading = YES;
        [jhc GetPersonListonef:(jhc.nextCursorone++) + 1];
    }];
    [self.tableView2 footerBeginRefreshing];
}
- (void)GetPersonListone:(NSInteger)nextCursorone
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=A25D4B33-B4E7-4855-9693-958D39D4E41B&c=data&page=%ld&type=10",nextCursorone];
    //        // 获取网络数据
            [NetwordHandler requestWithURL:url_string completion:^(id result) {
                NSDictionary *dic = result;
                NSLog(@"%@",result);
                if (self.isUpLoading == NO) {
                    //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
                    [self.picArr1 removeAllObjects];
                }
                self.picArr1 = [NSMutableArray array];
                NSMutableArray *a = [NSMutableArray array];
                a = [dic objectForKey:@"list"];
                for (NSDictionary *d in a) {
                    JHCharacterObject *oc = [[JHCharacterObject alloc] initWithDic:d];
                    [_picArr1 addObject:oc];
                }
                [self.tableView2 headerEndRefreshing];
                [self.tableView2 footerEndRefreshing];
                [self.tableView2 reloadData];
                [self.pendulum removeFromSuperview];
                
            }];

}
- (void)GetPersonListonef:(NSInteger)nextCursorone
{
    NSString *url_string = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=A25D4B33-B4E7-4855-9693-958D39D4E41B&c=data&page=%ld&type=10",nextCursorone];
     // 获取网络数据
    [NetwordHandler requestWithURL:url_string completion:^(id result) {
        NSDictionary *dic = result;
        NSLog(@"%@",result);
        NSMutableArray *a = [NSMutableArray array];
        a = [dic objectForKey:@"list"];
        [a removeObjectAtIndex:0];
        for (NSDictionary *d in a) {
            JHCharacterObject *oc = [[JHCharacterObject alloc] initWithDic:d];
            [_picArr1 addObject:oc];
        }
        [self.tableView2 footerEndRefreshing];
        [self.tableView2 reloadData];
        
    }];

}














- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
